#define _CRT_SECURE_NO_WARNINGS
#include "SeqList.h"

//初始化:
void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->capacity = ps->size = 0;
}

//判断空间够不够，不够就扩容:
void SLCheckCapacity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLDataType* temp = (SLDataType*)realloc(ps->arr, newcapacity * sizeof(SLDataType));
		if (temp == NULL)
		{
			perror("realloc");
			exit(1);
		}
		ps->arr = temp;
		ps->capacity = newcapacity;
	}
}

//头插:
void SLPushFront(SL* ps,SLDataType x)
{
	SLCheckCapacity(ps);//内含assert(ps)
	//从后向前移
	for (int i = ps->size; i > 0 ; i--)
	{
		ps->arr[i] = ps->arr[i - 1];//最后:arr[1]=arr[0]
	}
	ps->arr[0] = x;
	ps->size++;
}

//打印:
//void SLPrint(SL ps)
//{
//	for (int i = 0; i < ps.size; i++)
//	{
//		printf("%d ", ps.arr[i]);
//	}
//	printf("\n");
//}

//尾插:
void SLPushBack(SL* ps, SLDataType x)
{
	SLCheckCapacity(ps);
	ps->arr[ps->size] = x;
	ps->size++;
}

//头删:
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);
	for (int i = 0; i < ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//尾删:
void SLPopBack(SL* ps)
{
	assert(ps);
	ps->size--;
}

//指定位置插入数据:
void SLInsert(SL* ps, int pos, SLDataType x)
{
	SLCheckCapacity(ps);
	assert(pos >= 0 && pos <= ps->size);
	//向后移动:
	for (int i = ps->size; i >pos ; i--)
	{
		ps->arr[i] = ps->arr[i-1];
		//最后:[pos+1]=[pos]
	}
	ps->arr[pos] = x;
	ps->size++;
}

//指定位置删除数据:
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(ps->size);
	for (int i = pos; i < ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//查找数据:
//int SLFind(SL* ps, SLDataType x)
//{
//	assert(ps);
//	for (int i = 0; i < ps->size; i++)
//	{
//		if (ps->arr[i] == x)
//		{
//			return i;
//		}
//	}
//	return -1;
//}

//销毁:
void SLDestroy(SL* ps)
{
	if (ps->arr)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}